var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var expressJWT = require("express-jwt");
var md5 = require("md5");
const session = require("express-session");
const { ServiceErr, ForbiddenError, UnknownError } = require("./utils/errors");
//数据库引入
require("dotenv").config(); //环境变量读取
require("./dao/db"); //连接/同步数据库
require("express-async-errors"); //异步错误捕获

var app = express();
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
  })
);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

//验证token
app.use(
  expressJWT
    .expressjwt({
      secret: md5(process.env.JWT_SECRYT),
      algorithms: ["HS256"],
    })
    .unless({
      //不需要验证token的路由
      path: [
        {
          url: "/api/admin/login",
          method: ["POST"],
        },
        {
          url: "/res/captcha",
          method: ["GET"],
        },
        {
          url: "/api/banner",
          method: ["GET"],
        },
        {
          url: "/api/blogtype",
          method: ["GET"],
        },
        {
          url: "/api/blog",
          method: ["GET"],
        },
        {
          url: /\/api\/blog\/d/,
          method: ["GET"],
        },
        {
          url: "/api/project",
          method: ["GET"],
        },
        {
          url: "/api/comment",
          method: ["GET", "POST"],
        },
        {
          url: "/api/message",
          method: ["GET", "POST"],
        },
        {
          url: "/api/about",
          method: ["GET"],
        },
        {
          url: "/api/setting",
          method: ["GET"],
        },
      ],
    })
);

//路由配置
app.use("/api/admin", require("./routes/admin")); //管理员
app.use("/res/captcha", require("./routes/captcha")); //验证码
app.use("/api/banner", require("./routes/banner")); //首页
app.use("/api/upload", require("./routes/uploads")); //图片上传接口
app.use("/api/blogtype", require("./routes/blogType")); //文章分类
app.use("/api/blog", require("./routes/blog")); //文章
app.use("/api/project", require("./routes/project")); //项目
app.use("/api/comment", require("./routes/comment")); //文章评论
app.use("/api/message", require("./routes/message")); //留言板
app.use("/api/about", require("./routes/about")); //关于页面
app.use("/api/setting", require("./routes/setting")); //全局配置

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.send(new ForbiddenError("未登录或登录过期").toResponseJSON());
  } else if (err instanceof ServiceErr) {
    res.send(err.toResponseJSON());
  } else {
    console.log(err);
    res.send(new UnknownError().toResponseJSON());
  }
});

module.exports = app;
